// pages/search-page/index.js
import
debounce
from "../../../utils/debounce"

import {
  APISearch
} from "../../../service/api_search"

import stringToNodes from "../../../utils/string-to-nodes"

const debounceGetSearchSuggest = debounce(APISearch.getSearchSuggest, 500, false)

Page({

  /**
   * 页面的初始数据
   */
  data: {
    hotKeyWords: [],
    searchValue: "", // 搜索框输入的值
    suggestData: [], // 搜索出来的列表数据
    suggestNodes: [], // rich-text节点数据
    resultSongs: [] // 搜索的结果
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getPageData()
  },

  getPageData() {
    APISearch.getHotKeyWords().then(res => {
      this.setData({
        hotKeyWords: res.result.hots
      })
    })
  },


  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  handleSearchChange(event) {
    const searchValue = event.detail;
    this.setData({
      searchValue
    })
    // 1 searchValue 为空的情况下
    if (!searchValue) {
      this.setData({
        suggestData: [],
        suggestNodes: [],
        resultSongs: []
      })
      debounceGetSearchSuggest.cancel()
      return
    }

    // 2  searchValue 不为空的情况下 搜索建议 suggestData
    debounceGetSearchSuggest(this.data.searchValue).then(res => {
      // 1 有结果赋值给 suggestData
      const suggestData = Object.keys(res.result).length ? res.result.allMatch : []
      this.setData({
        suggestData
      })

      // 2 有结果赋值给 suggestNodes
      const suggestKeywords = suggestData.map(item => item.keyword)
      const suggestNodes = [] // 存放所有节点的地方
      suggestKeywords.forEach(keyword => {
        const nodes = stringToNodes(keyword, searchValue)
        suggestNodes.push(nodes)
      })
      this.setData({
        suggestNodes
      })
    })
  },

  // 1 点击键盘确认搜索
  handleSearchValue(event) {
    this.getResultBySerach()
  },

  // 2 点击 搜索建议列表中的某一项搜索
  handleSearchBySuggest(event) {
    const keyword = event.currentTarget.dataset.keyword
    this.setData({
      searchValue: keyword
    })
    this.getResultBySerach()
  },

  // 3 点击热门搜索关键字 搜索


  //
  getResultBySerach() {
    APISearch.getResultBySearchKeyword(this.data.searchValue).then(res => {
      const resultSongs = res.result.songs
      this.setData({
        resultSongs
      })
    })
  }
})